/*
 * Annuaire.java
 *
 * Created on 14 mai 2007, 14:55
 */

package bibliotheque.nameserver.gui;

import bibliotheque.events.ErrorOccuredEvent;
import bibliotheque.events.ErrorOccuredListener;
import bibliotheque.events.StateChangedEvent;
import bibliotheque.events.StateChangedListener;
import bibliotheque.nameserver.*;
import bibliotheque.nameserver.parser.ParserNameServer;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JDialog;
import javax.swing.JFileChooser;

/**
 *
 * @author  guillaume
 */
public class NameServerGui extends javax.swing.JFrame implements StateChangedListener,ErrorOccuredListener {
    
    private NameServer annuaire;
    
    /** Creates new form Annuaire */
    public NameServerGui() {
        try {
            this.annuaire = new NameServer();
            this.annuaire.AddStateChangedListener(this);
            this.annuaire.AddErrorOccuredListener(this);
            this.setTitle("Annuaire");
            initComponents();
        } catch (Exception ex) {
            
        }
    }
    
    public String GetService() {
        try {
            return(this.jComboBoxServices.getSelectedItem().toString());
        } finally {
            return("");
        }
    }
    
    private void EnableUpdate() {
        this.StopButton.setEnabled(!this.jLabelEtat.getText().startsWith("STOP"));
        this.StartButton.setEnabled(
                this.jLabelEtat.getText().equals("STOP") &&
                this.jComboBoxServices.getSelectedItem() != null &&
                this.jTextFieldRmiAddress.getText().matches("([0-9]{1,3}+.){3}+[0-9]{1,3}+") &&
                this.jTextFieldRmiPort.getText().matches("[0-9]{1,5}+"));
        this.BrowseButton.setEnabled(this.jLabelEtat.getText().equals("STOP"));
        this.jTextFieldFile.setEnabled(this.jLabelEtat.getText().equals("STOP"));
        this.jTextFieldRmiAddress.setEnabled(this.jLabelEtat.getText().equals("STOP"));
        this.jTextFieldRmiPort.setEnabled(this.jLabelEtat.getText().equals("STOP"));
        this.jComboBoxServices.setEnabled(this.jLabelEtat.getText().equals("STOP"));
    }
    
    public void StateChanged(StateChangedEvent event) {
        
        jLabelEtat.setText(event.GetState());
        this.EnableUpdate();
    }
    
    public void ErrorOccured(ErrorOccuredEvent event) {
        this.jTextAreaConsole.append(event.GetError() + "\n");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        StartButton = new javax.swing.JButton();
        StopButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabelEtat = new javax.swing.JLabel();
        jComboBoxServices = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldRmiPort = new javax.swing.JTextField();
        jTextFieldRmiAddress = new javax.swing.JTextField();
        jTextFieldFile = new javax.swing.JTextField();
        BrowseButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaConsole = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        StartButton.setText("Start");
        StartButton.setEnabled(false);
        StartButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StartButtonActionPerformed(evt);
            }
        });

        StopButton.setText("Stop");
        StopButton.setEnabled(false);
        StopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StopButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Fichier de configuration :");

        jLabel2.setText("Etat : ");

        jLabelEtat.setText("STOP");

        jLabel5.setText("Adresse du rmiregistry :");

        jLabel6.setText("Port du rmiregistry :");

        jTextFieldRmiPort.setText("2222");
        jTextFieldRmiPort.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextFieldRmiPortCaretUpdate(evt);
            }
        });

        jTextFieldRmiAddress.setText("127.0.0.1");
        jTextFieldRmiAddress.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextFieldRmiAddressCaretUpdate(evt);
            }
        });

        jTextFieldFile.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextFieldFileCaretUpdate(evt);
            }
        });

        BrowseButton.setText("Browse");
        BrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BrowseButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Service :");

        jTextAreaConsole.setColumns(20);
        jTextAreaConsole.setRows(5);
        jTextAreaConsole.setEnabled(false);
        jScrollPane1.setViewportView(jTextAreaConsole);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxServices, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel1))
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jTextFieldFile, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BrowseButton))
                            .addComponent(jTextFieldRmiPort, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                            .addComponent(jTextFieldRmiAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(StartButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(73, 73, 73)
                        .addComponent(StopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelEtat, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxServices, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextFieldRmiAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextFieldRmiPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(BrowseButton)
                    .addComponent(jTextFieldFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(StartButton)
                    .addComponent(StopButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabelEtat))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        JDialog dialog = new JDialog(this, "Waiting for the Name_Server to stop...");
        dialog.setSize(300,50);
        dialog.setLocation(50,50);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
        this.annuaire.StopService();
        while(!this.jLabelEtat.getText().equals("STOP"));
    }//GEN-LAST:event_formWindowClosing

    private void jTextFieldRmiPortCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextFieldRmiPortCaretUpdate
        this.EnableUpdate();
    }//GEN-LAST:event_jTextFieldRmiPortCaretUpdate

    private void jTextFieldRmiAddressCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextFieldRmiAddressCaretUpdate
        this.EnableUpdate();
    }//GEN-LAST:event_jTextFieldRmiAddressCaretUpdate
    
    private void jTextFieldFileCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextFieldFileCaretUpdate
        
        try {
            File file = new File(this.jTextFieldFile.getText());
            if (!file.exists()) throw new Exception();
            else {
                ArrayList<String> list;
                list = ParserNameServer.GetServiceList(file);
                Iterator<String> iter = list.iterator();
                while (iter.hasNext()) {
                    this.jComboBoxServices.addItem(iter.next());
                }
            }
        } catch(Exception ex) {
            this.jComboBoxServices.removeAllItems();
        } finally {
            this.EnableUpdate();
        }
    }//GEN-LAST:event_jTextFieldFileCaretUpdate
    
    private void BrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BrowseButtonActionPerformed
// TODO add your handling code here:
        
        /* Creation du fileChooser */
        JFileChooser filechooser = new JFileChooser();
        
        /* Creation du filtre de fichiers */
        filechooser.addChoosableFileFilter(new XNCFilter());
        
        /* Affichage de la boite de dialogue */
        filechooser.setCurrentDirectory(new File("./src/bibliotheque/config"));
        if(filechooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
            this.jTextFieldFile.setText(filechooser.getSelectedFile().getAbsolutePath());
    }//GEN-LAST:event_BrowseButtonActionPerformed
        
    private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StopButtonActionPerformed
            this.annuaire.StopService();
    }//GEN-LAST:event_StopButtonActionPerformed
    
    private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartButtonActionPerformed
        this.annuaire.StartService(new File(this.jTextFieldFile.getText()), this.jComboBoxServices.getSelectedItem().toString(), this.jTextFieldRmiAddress.getText(), Integer.parseInt(this.jTextFieldRmiPort.getText()));
    }//GEN-LAST:event_StartButtonActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NameServerGui().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BrowseButton;
    private javax.swing.JButton StartButton;
    private javax.swing.JButton StopButton;
    private javax.swing.JComboBox jComboBoxServices;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelEtat;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaConsole;
    private javax.swing.JTextField jTextFieldFile;
    private javax.swing.JTextField jTextFieldRmiAddress;
    private javax.swing.JTextField jTextFieldRmiPort;
    // End of variables declaration//GEN-END:variables
    
}
